<template>
  <div class="about">
    <el-card class="updateCard">
      <div style="width: 400px;margin: 0 auto">
        <el-avatar style="display: inline-block" :src="localUser.avatar" icon="el-icon-user-solid" :size="150"></el-avatar>
      </div>
      <el-upload
          class="avatar-uploader"
          action="http://localhost:9285/resource/upload/image"
          :show-file-list="false"
          :on-success="handleUploadSuccess">
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <el-button @click="updateAvatar">上传头像</el-button>
      <p style="color: #409EFF;margin-top: 5px">温馨提示：更换头像有时需要刷新才能生效</p>
    </el-card>
    <el-card class="updateCard">
      <el-form :model="localUserUpdate" :rules="rules" ref="localUserUpdate"  style="padding:0 30%">
        <el-form-item
            label="旧密码：" prop="oldPassword">
          <el-input  style="width: 70%"
                     type="password"
                     show-password
                     v-model="localUserUpdate.oldPassword"
                     placeholder="请输入新密码"></el-input>
        </el-form-item>
        <el-form-item
            label="新密码：" prop="newPassword">
          <el-input  style="width: 70%"
                     type="password"
                     show-password
                     v-model="localUserUpdate.newPassword"
                     placeholder="请输入新密码"></el-input>
        </el-form-item>
        <el-form-item
            label="再次输入：">
          <el-input  style="width: 70%;margin-left: -1%"
                     type="password"
                     show-password
                     v-model="rePassword"
                     placeholder="请输入新密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updateLocalPassword('localUserUpdate')">修改密码</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import router from "@/router";

export default {
  data(){
    return{
      imageUrl:"",
      imageOld:"http://localhost:9285/2023/06/11/f6a38b59-0a46-4176-93fd-4d423ff975b9.png",
      lookUpload:false,
      localUser:{
        avatar:'',
      },
      localUserUpdate:{
        id:'',
        oldPassword:'',
        newPassword:'',
      },
      rePassword:'',
      rules:{
        oldPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur' },
          {pattern:/^([1-9A-Za-z]*)$/,message:'请输入以字母和数字组成的密码',trigger: 'blur'}
        ],
        newPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur' },
          {pattern:/^([1-9A-Za-z]*)$/,message:'请输入以字母和数字组成的密码',trigger: 'blur'}
        ],
      }
    }
  },
  methods:{
    handleUploadSuccess(response) {
      this.imageUrl = response.url;
    },
    LoadUser(){
      this.localUser = JSON.parse(localStorage.getItem("localUser"));
      console.log(this.localUser.id)
      this.localUserUpdate.id = this.localUser.id;
    },
    updateAvatar(){
      /*user-update-avatar*/
      let url = "http://localhost:9281/user-update-avatar/";
      console.log(this.localUser.id)
      let user = {
        id:this.localUser.id,
        avatar: this.imageUrl
      }
      console.log(url);
      let formData = this.qs.stringify(user);
      let jwt = localStorage.getItem("localJwt");
      this.axios
          .create({
            'headers':{
              'Authorization':jwt
            }
          }).post(url,formData).then((response)=> {
        let jsonResult = response.data;
        if(jsonResult.state==20000){
          this.$message({
            showClose: true,
            message: '修改成功',
            type: 'success'
          });
          this.localUser.avatar = this.imageUrl;
          localStorage.setItem("localUser",JSON.stringify(this.localUser));
          localStorage.setItem("loadBank",1);
          location.reload()
          this.$router.push('/student')
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        }else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      })

    },
    updateLocalPassword(formName){
      this.$refs[formName].validate((valid) => {
            if (valid) {
              if (this.rePassword !== this.localUserUpdate.newPassword) {
                alert("两次密码不一致！！")
                return;
              }
              let url = "http://localhost:9281/local-password-update/";
              console.log(url);
              let formData = this.qs.stringify(this.localUserUpdate);
              let jwt = localStorage.getItem("localJwt");
              this.axios
                  .create({
                    'headers': {
                      'Authorization': jwt
                    }
                  }).post(url, formData).then((response) => {
                let jsonResult = response.data;
                if (jsonResult.state == 20000) {
                  this.$message({
                    showClose: true,
                    message: '修改成功',
                    type: 'success'
                  });
                  if (jsonResult.jwt!=null){
                    localStorage.setItem("localJwt",jsonResult.jwt);
                  }
                }else if(jsonResult.state==70100){
                  this.$alert(jsonResult.message, '错误', {
                    confirmButtonText: '确定',
                    callback: action => {
                    }
                  });
                  this.$router.push('/')
                } else {
                  this.$alert(jsonResult.message, '错误', {
                    confirmButtonText: '确定',
                    callback: action => {
                    }
                  });
                }
              })
            }
          }
      )

    },
  },
  mounted() {
    this.LoadUser();
  }
}
</script>
<style>
.updateCard{
  width: 70vw;margin: 0 auto;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
